package demo2;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author liangzai
 * @Description:
 */
public class BinaryTree {
    public void levelOrder(TreeNode root){
        if(root==null){
            return ;
        }
        Queue<TreeNode> list = new LinkedList<>();
        list.offer(root);
        while(!list.isEmpty()){
            TreeNode pcur = list.poll();
            System.out.print(pcur.val+" ");
            if(pcur.left!=null){
                list.offer(pcur.left);
            }
            if(pcur.right!=null){
                list.offer(pcur.right);
            }
        }
        System.out.println();
    }

    //层序遍历二叉树(每一行为一组)
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Character> list1 = new ArrayList<>(size);
            while(size>0) {
                TreeNode pcur = queue.poll();
                list1.add(pcur.val);
                if (pcur.left != null) {
                    queue.offer(pcur.left);
                }
                if (pcur.right != null) {
                    queue.offer(pcur.right);
                }
                size--;
            }
            list.add(list1);
        }
        return list;
    }
}
